package com.pmdb.util;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import com.pmdb.core.data.Genre;

public class GenreUtil {

   private static final Logger LOG = Logger.getLogger(GenreUtil.class);
   
   private static final int NUM_ITEMS = 7;

   private static final String[] countries = new String[] {
      "Drama",
      "Sci-Fi",
      "Crime",
      "Thriller",
      "Action",
      "Historical",
      "Comedy"};

   private static int genreIdx = -1;
   private static List<Genre> items = new ArrayList<Genre>();
   private EntityManager em = null;

   public GenreUtil(EntityManager em) {
      this.em = em;
   }

   public void generateGenre() {
     for (int i = 0; i < NUM_ITEMS; ++i) {
       items.add(createGenre());
     }
   }

   public Genre getGenre(int index) {
     if (index >= items.size()) {
       return null;
     }
     return items.get(index);
   }

   public int getGenreCount() {
     return items.size();
   }

   private Genre createGenre() {
     genreIdx++;
     return new Genre(countries[genreIdx]);
   }

   private Genre createGenre(String name) {
     Genre newGenre = new Genre(name);
     em.persist(newGenre);
     return newGenre;
   }

   public Genre findGenreByName(String name) {
      Query genreByName = em.createQuery("from Genre g where g.name like :name");
      genreByName.setParameter("name", name);
      
      if(genreByName.getResultList().size() == 0) {
         LOG.debug("Not Found: " + name);
         return null;
      }
      else {
         LOG.debug("Found: " + name);
         return (Genre)genreByName.getSingleResult();
      }
   }

   public Genre findOrCreate(String name) {
      Genre genre = this.findGenreByName(name);
      if(genre == null) {
         genre = this.createGenre(name);
         LOG.debug("Genre: " + name + " not found! (created)");
      }
      return genre;
   }
}
